package server.price;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

import server.Logger;
import server.db.DataBase;

public class PriceController {
	private HashMap<String, Price> prices;
	private DataBase db;
	private String[] currs;
	private String[] currPairs;
	
	/**
	 * Create a new price controller
	 */
	private PriceController() {
		db = DataBase.getInstance();
		prices = new HashMap<String, Price>();
		
		try {
			initializePrices();
			setCurrPairs();
			Logger.getInstance().addLog("PriceController has started", 1);
		} catch (SQLException e) {
			Logger.getInstance().addError("PriceController could not be started", 1);
		}
	}
	
	/**
	 * Put all possible price combinations into the hashMap
	 * @throws SQLException
	 */
	private final void initializePrices() throws SQLException {		
		ResultSet rs = db.doQuery("SELECT sym FROM currencies ORDER BY id ASC");

		currs = new String[DataBase.getRows(rs)];
		
		int currCounter = 0;
		do {
			currs[currCounter] = rs.getString("sym");
			currCounter++;
		} while (rs.next());
		
		for (String cur1 : currs) {
			for (String cur2 : currs) {
				if (!cur1.equals(cur2)) {
					prices.put(cur1+cur2, new Price(cur1,cur2));
				}
			}
		}
	}
	
	/**
	 * Create an array of non-redundant currency pairs
	 */
	private void setCurrPairs() {
		currPairs = new String[((currs.length) * (currs.length - 1)) / 2];
		int counter = 0;
		
		for (int x = 0; x < currs.length - 1; x++) {
			for (int y = x + 1; y < currs.length; y++) {
				currPairs[counter++] = currs[x] + currs[y];
			}
		}
	}
	
	/**
	 * Return the price specified by cur1 and cur2
	 * @param cur1	Base currency
	 * @param cur2	Quote currency
	 * @return	Price
	 */
	public Price getPrice(String cur1, String cur2) {
		return getPrice(cur1+cur2);
	}
	
	/**
	 * Return the price based on curPaid
	 * @param curPair	Currency pair requested
	 * @return	The currency pair requested or null if no such pair exists
	 */
	public Price getPrice(String curPair) {
		return (prices.containsKey(curPair)) ? prices.get(curPair) : null;
	}
	
	public String[] getCurrencies() { return currs; }
	public String[] getCurrPairs() { return currPairs; }
	
	/**
	 * A class to hold the only instance of PriceController
	 */
	private static class PriceControllerHolder { 
		private final static PriceController INSTANCE = new PriceController();
	}
 
	/**
	 * @return The only instance of PriceController
	 */
	public static PriceController getInstance() {
		return PriceControllerHolder.INSTANCE;
	}
}
